package com.tim.helper.file;

import com.tim.util.StringAnalysisUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;

public class FileHelper {

	@Test// 检索包含指定内容的文件
	public void findFile() throws IOException {
		String dir = "D:\\settings";
		String suffix = "";
		String searchStr = "git";
		Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
				String fileName = path.getFileName().toString();
//				System.out.println(fileName);
				if(fileName.endsWith(suffix)) {
					try {
						List<String> contents = Files.readAllLines(path);
						String htmlTitle = "";
						for (int i = 0; i < contents.size(); i++) {
							String item = contents.get(i).trim();
							if(".html".equals(suffix) && item.startsWith("<title>")) {
								htmlTitle = item.replace("<title>", "").replace("</title>", "");
							}
							if(item.contains(searchStr)) {
								System.out.println(htmlTitle+"；"+path);
								break;
							}
						}
					}catch (Exception e) {
						e.printStackTrace();
						System.out.println(path);
					}
					
				}
				return FileVisitResult.CONTINUE;
			}
			
		});
	}
	
	@Test// 批量替换
	public void batchEditFile() throws IOException {
		String dir = "D:/IntelliJ IDEA/workSpace/qft-all/qft-consumer/qft-consumer-web-platform/src/main/resources";
		String suffix = ".js";
		String content = "function setTerm";
		System.out.println("batchEditFile");
		Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
				String fileName = path.getFileName().toString();
//				System.out.println(fileName);
				if(fileName.endsWith(suffix)) {
					try {
						List<String> contents = Files.readAllLines(path);
						boolean flag = false;
						for (int i = 0; i < contents.size(); i++) {
							String item = contents.get(i).trim();
							if(item.contains(content)) {
								String filePath = path.toString();
								String content = contents.get(i);
								content = content +String.format("\n console.log('%s');", fileName);
//								filePath = filePath.substring(filePath.indexOf("static\\"));
								contents.set(i, content);
								flag = true;
								System.out.println(fileName);
//								break;
							}
						}
						if(flag) {
							Files.write(path, contents);
						}
					}catch (Exception e) {
						e.printStackTrace();
						System.out.println(path);
					}
					
				}
				return FileVisitResult.CONTINUE;
			}
			
		});
	}

	@Test
	public void printServiceXmind() throws Exception {
		int projectIdx = 3;
		String[] projects = {"biz-pig-api","biz-pig-mis-api","biz-pig-pub-api","biz-pig-report-api"};
		String[] pkgs = {"","mis","pub","report"};
		String project = projects[projectIdx];
		String pkg = pkgs[projectIdx];
		Path path = Paths.get("E:\\gitlab\\exodus\\biz\\biz-pig", project, "src\\main\\java\\com\\xqxc\\api\\pig", pkg);
		// 直接赋值path，处理其他项目
		String interfaceFlag = " interface ";
		Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
			String padding = "";
			public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
					throws IOException
			{
				int count = dir.getNameCount()- path.getNameCount();// 路径差
				if(count>0){
					padding = StringUtils.repeat("\t", count-1);
					System.out.println(padding+dir.getName(dir.getNameCount()-1));
				}
				return FileVisitResult.CONTINUE;
			}

			public FileVisitResult visitFile(Path path, BasicFileAttributes attrs)
					throws IOException
			{
				if(!path.toString().endsWith(".java")){
					return FileVisitResult.CONTINUE;
				}
				List<String> content = Files.readAllLines(path);
				boolean clsFlag = false;
				boolean outterFlag = false;
				String annoVal = "";
				for (int i = 0; i < content.size(); i++) {
					String line = content.get(i).trim();
					if(StringUtils.isBlank(line) || line.startsWith("import")){
						continue;
					}
					// 处理注释；单行、多行
					if(line.startsWith("/**")){
						if(line.endsWith("*/")){
							annoVal = line.substring(3, line.length()-2);
						}else{
							// 取后续行
							do{
								line = content.get(++i).trim();
								if(line.length()<2){
									continue;
								}
								annoVal = line.substring(1).trim()
										.replaceAll("(?i)@describe", "")
										.replaceAll("\\*/$", "")
										.trim();
								if(annoVal.contains("@")){
									annoVal="";
								}
								break;
							}while(line.endsWith("*/"));
						}
					}
					// 处理@Api注解
					if(line.startsWith("@Api")){
						String info = StringAnalysisUtil.getAnnoValue(line);
						if(StringUtils.isNotBlank(info)){
							annoVal = info;
						}
					}
					// 处理@CMD
					if(line.startsWith("@CMD")){
						String info = StringAnalysisUtil.getAnnoValue(line);
						outterFlag = true;
						if(StringUtils.isNotBlank(info)){
							annoVal = info;
						}
					}

					// 处理接口名
					if(!clsFlag && line.startsWith("public")){
						// 跳过非接口
						if(!line.contains(" interface ")){
							return FileVisitResult.CONTINUE;
						}
						int idx = line.indexOf(interfaceFlag);
						if(idx>-1){
							String[] strs = line.substring(idx+interfaceFlag.length())
									.trim().split("\\s+");
							System.out.println(padding+"\t"+strs[0]);
							clsFlag=true;
						}
					}
					// 处理方法名。考虑多行方法签名
					if(line.endsWith(";") && line.contains("(") && line.contains(")")){
						// 处理多行方法签名
						int idx = line.indexOf('(');
						String pre = line.substring(0, idx).trim();
						int temp = i;
						while(idx<8||pre.contains("@")||pre.split("\\s+").length<2){
							line = content.get(i--).trim()+" "+line;
							idx = line.indexOf('(');
							pre = line.substring(0, idx).trim();
						}
						i=temp;
						
						String method = StringAnalysisUtil.getMethodInfo(line)[1].trim();
						if(!method.matches("\\w+")){
							continue;
						}
						System.out.println(padding+"\t\t"+annoVal+"；"+method+"；"+(outterFlag?"O":"I"));
						outterFlag = false;
						annoVal="";
					}

				}
				return FileVisitResult.CONTINUE;
			}


		});

	}

}
